package kassiopeia.plugin.crawler.filter;

import java.net.URL;
import java.util.Arrays;
import java.util.List;

import kassiopeia.plugin.Event;
import kassiopeia.plugin.ProcessorPlugin;

import org.apache.log4j.Logger;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;

public class DomainFilterPlugin extends ProcessorPlugin {

    private final String DOMAINS_PARAM = "allowed-domains";
    private final String OUTPUT = "out";
    private final Logger logger = Logger.getLogger(DomainFilterPlugin.class);

    private List<String> domains;

    @Override
    public void beforeTask() {
        logger.info("ContentFilterPlugin plugin constructed : " + getContext().getPluginInstanceId());

        String allowedMimeParam = getContext().getParameter(DOMAINS_PARAM);
        Iterable<String> elements = Splitter.on(" ").omitEmptyStrings().trimResults().split(allowedMimeParam);
        domains = Lists.newArrayList(elements);

        logger.debug("Allowed domains: " + Arrays.toString(domains.toArray(new String[0])));

    }

    @Override
    public void process(Event event) {
        URL url = getNotNullableEventBody(event, URL.class);

        String host = url.getHost();
        if(isDomainAllowed(host)) {
            logger.debug("Accepting event for domain: " + host);
            getContext().sendLocally(event, OUTPUT);
        } else {
            logger.debug("Discarding event for domain: " + host);
        }
    }

    private boolean isDomainAllowed(String host) {
        if(host == null) {
            return false;
        }

        for(String domain : domains) {
            if(host.endsWith(domain)) {
                return true;
            }
        }
        return false;
    }
}
